package cn.bdqn.smbms.controller;

import cn.bdqn.smbms.entity.Role;
import cn.bdqn.smbms.entity.User;
import cn.bdqn.smbms.service.RoleService;
import cn.bdqn.smbms.service.UserService;
import cn.bdqn.smbms.util.PageBean;
import cn.bdqn.smbms.util.UUIDUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    //显示添加用户
    @RequestMapping("/useradd.html")
    public String showAddUser() {
        return "useradd";
    }

    //添加用户
    @RequestMapping("/adduser.html")
    public String addUser(User user, HttpSession session, MultipartFile pic1,MultipartFile pic2 ){
        User userSession = (User) session.getAttribute("userSession");
        user.setCreatedBy(userSession.getId());
        String path= session.getServletContext().getRealPath("/statics"+File.separator+"upload");
        if(!pic1.isEmpty()&&!pic2.isEmpty()){
            String uuid1 = UUIDUtil.getUUId();//随机数
            String uuid2 = UUIDUtil.getUUId();//随机数
            File file = new File(path+File.separator+uuid1 +pic1.getOriginalFilename());
            File file2 = new File(path+File.separator+uuid2+pic2.getOriginalFilename());
            try {
                pic1.transferTo(file);
                pic2.transferTo(file2);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        int ret = userService.addUser(user);
        if (ret > 0) {
            return "success1";
        } else {
            return "error1";
        }
    }

    //id查询
    @GetMapping("/view/{id}")
    public String showId(
            @PathVariable
                    Integer id,
            Model model
    ) {
        User user = userService.findById(id);
        model.addAttribute("user", user);
        return "usermodify";
    }

    //修改用户
    @RequestMapping("/modify.html")
    public String updateUser(User user, HttpSession session) {
        User userSession = (User) session.getAttribute("userSession");
        user.setModifyBy(userSession.getId());
        int ret = userService.updateUser(user);
        if (ret > 0) {
            return "success1";
        } else {
            return "error1";
        }
    }

    //删除用户
    @ResponseBody
    @DeleteMapping(value = "/del/{uid}")
    public Map<String, Object> delUser(
            @PathVariable("uid")
                    Integer uid
    ) {
        Map<String, Object> map = new HashMap<String, Object>();
        //查一下有无此人
        User user = userService.findById(uid);
        if (user == null) {
            map.put("ret", "notexist");
        } else {
            int ret = userService.delUser(uid);
            if (ret > 0) {
                map.put("ret", "true");
            } else {
                map.put("ret", "false");
            }
        }
        return map;
    }

    //利用ajax显示角色
    @ResponseBody
    @RequestMapping(value = "/getRoleList", produces = {"application/json;charset=UTF-8"})
    public List<Role> checkUserCode2() {
        List<Role> roleList = roleService.findAll();
        return roleList;
    }

    //ajax查看用户
    @ResponseBody
    @GetMapping(value = "/showUser/{id}", produces = {"application/json;charset=UTF-8"})
    public User showUserId(
            @PathVariable
                    Integer id) {
        User user = userService.findById(id);
        return user;
    }

    //利用ajax验证用户是否存在
    @ResponseBody
    @RequestMapping("/checkUserCode")
    public boolean checkUserCode(
            @RequestParam
                    String userCode
    ) {
        return userService.checkUserCode(userCode);
    }

    @RequestMapping("/userlist.html")
    public String showUserList(
            @RequestParam(value = "queryName", required = false)
                    String queryName,
            @RequestParam(value = "queryUserRole", required = false,defaultValue = "0")
                    Integer queryUserRole,
            @RequestParam(value = "pageNo", required = false, defaultValue = "1")
                    Integer pageNo, Model model
    ) {
        int pageSize = 3;
        PageBean<User> pageBean = userService.findByPage(queryName, queryUserRole, pageNo, pageSize);
        model.addAttribute("pageBean", pageBean);
        List<Role> roleList = roleService.findAll();
        model.addAttribute("roleList", roleList);
        if (queryName != null) {
            model.addAttribute("queryUserName", queryName);
        }
        if (queryUserRole != null && queryUserRole != 0) {
            model.addAttribute("queryUserRole", queryUserRole);
        }
        return "userlist";
    }

    //显示修改密码
    @RequestMapping("modifypwd.html")
    public String showModifyPwd() {
        return "pwdmodify";
    }

    //修改密码验证
    @ResponseBody
    @RequestMapping("/checkOldPwd.html")
    public Map<String, Object> modifyPwd(
            @RequestParam
                    String oldpassword,
            HttpSession session
    ) {
        User user = (User) session.getAttribute("userSession");
        Map<String, Object> map = new HashMap<String, Object>();
        if (oldpassword == null || oldpassword.equals("")) {
            map.put("result", "error");
        } else {
            if (user == null) {
                map.put("result", "sessionerror");
            } else {
                if (oldpassword.equals(user.getUserPassword())) {
                    map.put("result", "true");
                } else {
                    map.put("result", "false");
                }
            }
        }
        return map;
    }

    //修改密码
    @PostMapping("/domodify.html")
    public String pwdModify(
            @RequestParam
                    String newpassword,
            HttpSession session
    ) {
        User userSession = (User)session.getAttribute("userSession");
        userSession.setUserPassword(newpassword);
        userSession.setModifyBy(userSession.getId());
        int ret= userService.updateUser(userSession);
        if(ret>0){
            session.setAttribute("userSession",userSession);
            return "success1";
        }else {
            return "error1";
        }
    }
}